package com.example.demo.utils;

import com.example.demo.mapper.PutOrderMapper;
import com.example.demo.pojo.Order.PutOrders;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.UUID;

@Component
public class PutOrderUtils {

    @Resource
    private PutOrderMapper putOrderMapper;

    /**
     * 发送撤单信息到kafka时的内容
     *
     * @param order        撤单订单pojo类
     * @param customStatus 订单状态（撤单）
     * @return 消息体
     */
    public String createWithdrawOrderMessage(PutOrders order, String customStatus) {
        return String.format(
                "{"
                        + "\"orderId\": \"%s\", "
                        + "\"userId\": \"%d\", "
                        + "\"stockCode\": \"%s\", "
                        + "\"orderType\": \"%s\", "
                        + "\"price\": %.2f, "
                        + "\"quantity\": \"%d\", "
                        + "\"status\": \"%s\", "
                        + "\"time\": \"%s\""
                        + "}",
                order.getOrderId(),
                order.getUserId(),
                order.getStockCode(),
                order.getOrderType(),
                order.getPrice(),
                order.getQuantity(),
                customStatus,
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getTime())
        );
    }

    //生成挂单
    public PutOrders createAndSubmitOrder(Integer id, Integer userId, String orderStatus, String stockCode, String stockName, BigDecimal price, int quantity, int multiply) {
        PutOrders putOrders = new PutOrders();
        putOrders.setOrderId(id); // 绑定比赛id
        putOrders.setOrderCode(LocalDate.now().toString() + UUID.randomUUID()); // 设置订单代码
        putOrders.setUserId(userId); // 设置用户ID
        putOrders.setOrderType(orderStatus); // 设置订单状态
        putOrders.setStockCode(stockCode); // 设置股票代码
        putOrders.setOrderName(stockName); // 设置股票名称
        putOrders.setPrice(price); // 设置价格
        putOrders.setQuantity(quantity / multiply); // 设置数量
        putOrders.setUnexecutedQuantity(quantity / multiply); // 设置未执行数量，卖出订单未交易股票就为0
        putOrders.setOrderStatus("未交易"); // 设置订单状态为"未交易"
        putOrders.setTime(new Date()); // 设置时间

        int insert = putOrderMapper.insert(putOrders);
        if (insert > 0) {
            return putOrders;
        }
        return null;
    }

    /**
     * 删除挂单
     *
     * @param orderId 订单的 ID
     * @return 删除是否成功
     */
    public boolean deletePutOrder(Integer orderId) {
        int delete = putOrderMapper.deleteById(orderId);
        return delete > 0;
    }

}
